#include "../log.h"

#ifdef UNIX
# include <time.h>
#else
# include <windows.h>
#endif

#include "host.h"

#ifdef UNIX
u64 host_getTime()
{
    return clock();
}
#else
u64 host_getTime(u64 ticksPerSecond)
{
    u64 ticks;
    if (!QueryPerformanceCounter((LARGE_INTEGER *)&ticks))
        ticks = timeGetTime();
    return (u64)((double)ticks / (double)ticksPerSecond) * 1000000ULL;
}
#endif

Timer host_initTimer(u32 length, u8 repeat)
{
    Timer timer;
#ifdef UNIX
    timer.lastTime = host_getTime();
#else
    if (!QueryPerformanceFrequency((LARGE_INTEGER *)&(timer.ticksPerSecond)))
        timer.ticksPerSecond = 1000;
    timer.lastTime = host_getTime(timer.ticksPerSecond);
#endif
    timer.length = length * 1000;
    timer.repeat = repeat;
    timer.inited = 1;
    return timer;
}

u8 host_testTimer(Timer *timer)
{
    u32 time;
    if (!timer->inited)
        return 0;
#ifdef UNIX
    time = host_getTime();
#else
    time = host_getTime(timer->ticksPerSecond);
#endif
    if (time - timer->lastTime >= timer->length)
    {
        timer->lastTime = time;
        if (!timer->repeat)
            timer->inited = 0;
        return 1;
    }
    return 0;
}

void host_updateTimerTime(Timer *timer)
{
#ifdef UNIX
    timer->lastTime = host_getTime();
#else
    timer->lastTime = host_getTime(timer->ticksPerSecond);
#endif
}

